﻿
CREATE PROCEDURE [dbo].[balcon_UpdateSolduriInitialeConturi]
	@CodUnitate smallint, 
	@Cont dbo.TipCont
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

	SELECT @Cont = COALESCE(ContParinte,'N/A') FROM Conturi WHERE CodUnitate = @CodUnitate AND Cont = @Cont
	
	WHILE @Cont <> 'N/A'
	BEGIN
		--adauga parintele pentru jurnalul respectiv
		--IF NOT EXISTS(SELECT * FROM JurnaleSolduriInitiale a WHERE a.Cont=@Cont AND a.IDJurnal=@IDJurnal AND a.CodUnitate=@CodUnitate)
			--INSERT INTO JurnaleSolduriInitiale ([IDJurnal],[Cont],[CodUnitate],[DebitInitial],[CreditInital],[DebitPrecedent],[CreditPrecedent])
			--VALUES (@IDJurnal,@Cont,@CodUnitate,0,0,0,0) 
	
		--pentru cazul in care se sterg toate analiticele se pune pe zero
		UPDATE cnt SET cnt.DebitInitial = 0,cnt.CreditInitial = 0
		FROM Conturi cnt
		WHERE cnt.Cont = @Cont AND cnt.CodUnitate = @CodUnitate

		--modifica soldurile initiale parinte din tabela conturi
		UPDATE cnt SET
		 cnt.DebitInitial = 
			CASE 
				WHEN Tip='A' THEN jsip.DebitInitial 
				WHEN Tip='P' THEN 0 
				WHEN Tip='B' AND jsip.DebitInitial-jsip.CreditInitial>0 THEN jsip.DebitInitial-jsip.CreditInitial 
				WHEN Tip='B' AND jsip.DebitInitial-jsip.CreditInitial<0 THEN 0
				ELSE 0
			END,
			cnt.CreditInitial = 
			CASE 
				WHEN Tip='A' THEN 0 
				WHEN Tip='P' THEN jsip.CreditInitial
				WHEN Tip='B' AND jsip.DebitInitial-jsip.CreditInitial>0 THEN 0 
				WHEN Tip='B' AND jsip.DebitInitial-jsip.CreditInitial<0 THEN jsip.CreditInitial - jsip.DebitInitial
				ELSE 0
			END
		FROM Conturi cnt, 
		(SELECT COALESCE(SUM(DebitInitial),0) DebitInitial, COALESCE(SUM(CreditInitial),0) CreditInitial, ContParinte,CodUnitate FROM Conturi c 
		 WHERE ContParinte = @Cont AND CodUnitate = @CodUnitate
		 GROUP BY ContParinte,CodUnitate) jsip
		WHERE cnt.Cont = @Cont AND cnt.CodUnitate = @CodUnitate
		
		
		SELECT @Cont = ContParinte FROM Conturi WHERE CodUnitate = @CodUnitate AND Cont = @Cont
		
	END
	

END